package com.googlecode.spruce.plugins.core.rdbms;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.commons.dbutils.DbUtils;

import com.googlecode.spruce.core.DefaultPluginResult;
import com.googlecode.spruce.core.ServiceCheckPlugin;
import com.googlecode.spruce.core.ServiceCheckPluginResult;

public abstract class AbstractRdbmsServiceCheck implements ServiceCheckPlugin
{
    private String validationQuery;
    private String username;
    private String password;

    @Override
    public ServiceCheckPluginResult execute()
    {
        DefaultPluginResult result = new DefaultPluginResult(100);

        Connection connection = null;
        Statement stmt = null;

        try
        {
            final String url = getConnectionURL();

            connection = DriverManager.getConnection(url, this.username, this.password);
            stmt = connection.createStatement();

            final ResultSet rs = stmt.executeQuery(this.validationQuery);

            if (!rs.next())
            {
                result = new DefaultPluginResult("Validation query failed");
            }
        }
        catch (final Exception e)
        {
            result = new DefaultPluginResult(e);
        }
        finally
        {
            DbUtils.closeQuietly(stmt);
            DbUtils.closeQuietly(connection);
        }

        return result;
    }

    abstract protected String getConnectionURL();

    /**
     * @return the username
     */
    public String getUsername()
    {
        return username;
    }

    /**
     * @param username
     *            the username to set
     */
    public void setUsername(final String username)
    {
        this.username = username;
    }

    /**
     * @return the password
     */
    public String getPassword()
    {
        return password;
    }

    /**
     * @param password
     *            the password to set
     */
    public void setPassword(final String password)
    {
        this.password = password;
    }

    /**
     * @return the validationQuery
     */
    public String getValidationQuery()
    {
        return validationQuery;
    }

    /**
     * @param validationQuery
     *            the validationQuery to set
     */
    public void setValidationQuery(final String validationQuery)
    {
        this.validationQuery = validationQuery;
    }

}
